﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.IO;
using System.Data;

namespace WebApplication1
{
    public partial class FilesUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserInfo"] == null || ((Entity.UserInfo)Session["UserInfo"]).UserType != "admin")
            {
                Response.Redirect("Search.aspx");
            }
            if (!Page.IsPostBack)
            {

                //初始化文件夹信息

                InitFolderInfo();

                //初始化上传限制信息

                InitUploadLimit();

                //初始化列表框控件文件列表信息

                InitFileList();

                DataTable dt = new DataTable();
                SQLHelper.getRootTags(out dt);
                for (int ix = 0; ix < dt.Rows.Count; ix++)
                {
                    lbxTagType.Items.Add(dt.Rows[ix]["TagName"].ToString());
                }
            }

        }

        #region 初始化文件夹信息
        private void InitFolderInfo()
        {

            //从config中读取文件上传路径

            string strFileUpladPath = ConfigurationManager.AppSettings["FileUplodePath"].ToString();

            //如果上传文件夹不存在,则根据config创建一个

            if (!Directory.Exists(Server.MapPath(strFileUpladPath)))
            {

                Directory.CreateDirectory(Server.MapPath(strFileUpladPath));

            }

            //将虚拟路径转换为物理路径

            string strFilePath = Server.MapPath(strFileUpladPath);

            //从config里读取文件夹容量限制

            double iFolderSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FolderSizeLimit"]);

            //声明文件夹已经使用的容量

            double iFolderCurrentSize = 0;

            //获取文件夹中的所有文件

            FileInfo[] arrFiles = new DirectoryInfo(strFilePath).GetFiles();

            //循环文件获已经使用的容量

            foreach (FileInfo fi in arrFiles)
            {

                iFolderCurrentSize += Convert.ToInt32(fi.Length / 1024);

            }

            #region 第二种获得文件夹使用大小的方法

            //DirectoryInfo dir = new DirectoryInfo(strFilePath);

            //foreach (FileSystemInfo fi in dir.GetFileSystemInfos())

            //{

            //    FileInfo finf = new FileInfo(fi.FullName);

            //    iFolderCurrentSize += Convert.ToInt32(finf.Length / 1024);

            //}

            #endregion

            //把文件夹容量和以用文件夹容量赋值给标签

            lbl_FolderInfo.Text = string.Format("文件夹容量限制：{0}M，已用容量：{1}KB", iFolderSizeLimit / 1024, iFolderCurrentSize);

        }
        #endregion

        #region 初始化上传限制信息

        private void InitUploadLimit()
        {

            //从config中读取上传文件夹类型限制并根据逗号分割成字符串数组

            string[] arrFileTypeLimit = ConfigurationManager.AppSettings["FileTypeLimit"].ToString().Split(',');

            //从config中读取上传文件大小限制

            double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]);

            //遍历字符串数组把所有项加入项目编号控件

            for (int i = 0; i < arrFileTypeLimit.Length; i++)
            {

                bl_FileTypeLimit.Items.Add(arrFileTypeLimit[i].ToString());

            }

            //把文件大小限制赋值给标签

            lbl_FileSizeLimit.Text = string.Format("上传文件限制：{0:f2}M", iFileSizeLimit / 1024);

        }

        #endregion

        #region 初始化列表框控件文件列表信息

        private void InitFileList()
        {

            //从config中获取文件上传路径

            string strFileUpladPath = ConfigurationManager.AppSettings["FileUplodePath"].ToString();

            //将虚拟路径转换为物理路径

            string strFilePath = Server.MapPath(strFileUpladPath);

            //读取上传文件夹下所有文件

            FileInfo[] arrFile = new DirectoryInfo(strFilePath).GetFiles();

            //把文件名逐一添加到列表框控件

            DataTable dt = new DataTable();
            SQLHelper.getFileUpload(out dt);

            gdvFile.DataSource = dt;
            gdvFile.DataKeyNames = new string[] { "Id" };
            gdvFile.DataBind();




        }

        #endregion

        #region 判断文件大小限制

        private bool IsAllowableFileSize()
        {

            //从web.config读取判断文件大小的限制

            double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]) * 1024;

            //判断文件是否超出了限制

            if (iFileSizeLimit > m_FileUpload.PostedFile.ContentLength)
            {

                return true;

            }

            else
            {

                return false;

            }

        }

        #endregion

        #region 判断文件类型限制

        protected bool IsAllowableFileType()
        {

            //从web.config读取判断文件类型限制

            string strFileTypeLimit = ConfigurationManager.AppSettings["FileTypeLimit"].ToString();

            //当前文件扩展名是否包含在这个字符串中

            if (strFileTypeLimit.Contains(Path.GetExtension(m_FileUpload.FileName + ",").ToLower()))

                return true;

            else

                return false;

        }

        #endregion

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //判断用户是否选择了文件

            if (lbxTagType.SelectedItem == null)
            {
                Response.Write("<script>alert('请选择文件所属标签类型！');location.href='FilesUpload.aspx';</script>");
                return;
            }

            if (m_FileUpload.HasFile)
            {

                //调用自定义方法判断文件类型否符合

                if (IsAllowableFileType())
                {

                    //判断文件大小是否符合

                    if (IsAllowableFileSize())
                    {
                        
                        //从web.config中读取上传路径

                        string strFileUploadPath = ConfigurationManager.AppSettings["FileUplodePath"].ToString();

                        //从UploadFile控件中读取文件名

                        string strFileName = m_FileUpload.FileName;
                        string strOriginName = strFileName;
                        

                        //组合成物理路径

                        string strFilePhysicalPath = Server.MapPath(strFileUploadPath + "/") + strFileName;

                        //判断文件是否存在

                        while (File.Exists(strFilePhysicalPath))
                        {
                            strFileName = "[TT]" + strFileName;
                            strFilePhysicalPath = Server.MapPath(strFileUploadPath + "/") + strFileName;
                        }

                        m_FileUpload.SaveAs(strFilePhysicalPath);
                        SQLHelper.AddUploadFile(strFileName, DateTime.Now.ToString(), lbxTagType.SelectedItem.Text, ((Entity.UserInfo)Session["UserInfo"]).UserName, strOriginName);
                        Response.Write("<script>alert('上传成功！');location.href='FilesUpload.aspx';</script>");
                    }

                    else
                    {

                        Response.Write("<script>alert('文件大小不符合！');location.href='FilesUpload.aspx';</script>");
                        return;

                    }

                }

                else
                {

                    Response.Write("<script>alert('文件类型不符合！');location.href='FilesUpload.aspx';</script>");
                    return;

                }
            }
            else
            {
                Response.Write("<script>alert('请选择上传文件！');location.href='FilesUpload.aspx';</script>");
            }


        }

        protected void gdvFile_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string str = SQLHelper.getFileNameById( (Int32)gdvFile.DataKeys[e.RowIndex].Value);
            int i = SQLHelper.deleteFile(str);
            string strFileUploadPath = ConfigurationManager.AppSettings["FileUplodePath"].ToString();
            string strFilePhysicalPath = Server.MapPath(strFileUploadPath + "/") + str;
            System.IO.File.Delete(strFilePhysicalPath);
            Response.Redirect("~/FilesUpload.aspx");
        }
    }
}